package net;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.replay.ReplayingDecoder;

enum MyDecoderState {
	   READ_LENGTH,
	   READ_CONTENT;
}

public class ExtractFrame extends ReplayingDecoder<MyDecoderState> {
	
	   private int _lengthReading;
	   private int _LengthMax;

	   public ExtractFrame(int lengthMax) {
		   super(MyDecoderState.READ_LENGTH);
		   _LengthMax = lengthMax;
	   }
	   
	   @Override
	   protected Object decode(ChannelHandlerContext ctx,
			   Channel channel,
			   ChannelBuffer buf,
			   MyDecoderState state) throws Exception {
		   switch (state) {
		   case READ_LENGTH:
			   _lengthReading = buf.readInt();
			   if (_lengthReading > _LengthMax) {
				   channel.close();
				   return null;
			   }
			   checkpoint(MyDecoderState.READ_CONTENT);
		   case READ_CONTENT:
			   ChannelBuffer frame = buf.readBytes(_lengthReading);
			   checkpoint(MyDecoderState.READ_LENGTH);
			   return frame;
		   default:
			   throw new Error("Shouldn't reach here.");
		   }
	   }
}


